package ThreadingSafety;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *  原子类: 底层是基于CAS实现的. 线程安全且高效.
 *
 *  Java中已经封装好了, 可以直接拿来用. 最常见的场景是 多线程计数~~
 *
 */
public class TestDemo29 {
    public static void main(String[] args) throws InterruptedException {

        AtomicInteger count = new AtomicInteger(0);

        Thread t1 = new Thread(()-> {
            for (int i = 0; i < 5_0000; i++) {
                // 相当于 count++;
                count.getAndIncrement();

                // 相当于 ++count;
                //count.incrementAndGet();
                // 相当于 count--;
                // count.getAndDecrement();
                // 相当于 --count;
                //count.decrementAndGet();
            }
        });

        Thread t2 = new Thread(()-> {
            for (int i = 0; i < 5_0000; i++) {
                // 相当于 count++;
                count.getAndIncrement();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count.get());
    }
}
